import threading

from flask import render_template, current_app
from flask_mail import Message


def run(app, msg):
    from apps import mail
    with app.app_context():
        try:
            mail.send(msg)
        except Exception as e:
            print(str(e))


def send_mail(to, template, subject, **kwargs):
    msg = Message(subject=subject, recipients=[to], sender=current_app.config['MAIL_USERNAME'])
    msg.html = render_template(template, **kwargs)
    app = current_app._get_current_object()
    threading.Thread(target=run, args=(app, msg)).start()
